package handle

import (
	"fmt"
	"gitee.com/general252/ffmpeg-tool/convert"
	"gitee.com/general252/ffmpeg-tool/help"
	"github.com/gin-gonic/gin"
	"net/http"
	"path/filepath"
	"strconv"
	"strings"
)

type AudioHandle struct {
}

func NewAudioHandle() *AudioHandle {
	return &AudioHandle{}
}

func (tis *AudioHandle) Convert(c *gin.Context) {
	sse := help.NewSSE(c.Writer)

	var (
		codecId    string
		fileId     string
		sampleRate = 0
		channel    = 0
		bitRate    string
	)

	{
		var haveCodecId, haveFileId bool
		codecId, haveCodecId = c.GetQuery("codecId")
		fileId, haveFileId = c.GetQuery("fileId")
		if !haveCodecId || !haveFileId {
			c.JSON(http.StatusBadRequest, gin.H{
				"code": -1,
				"msg":  fmt.Sprintf("haveCodecId: %v, haveFileId: %v", haveCodecId, haveFileId),
			})
		}

		bitRate, _ = c.GetQuery("bitRate")
		strSampleRate, _ := c.GetQuery("sampleRate")
		strChannel, _ := c.GetQuery("channel")

		if v, err := strconv.Atoi(strSampleRate); err == nil {
			sampleRate = v
		}

		if v, err := strconv.Atoi(strChannel); err == nil {
			channel = v
		}
	}

	inputFilename := fmt.Sprintf("./uploads/%v", fileId)
	outputFile := fmt.Sprintf("./uploads/%v", strings.TrimSuffix(fileId, filepath.Ext(fileId)))

	h := convert.NewAudio()
	outFilename, err := h.Convert(c.Request.Context(), inputFilename, outputFile,
		0, 0,
		convert.AudioCodec(codecId), sampleRate, channel, bitRate,
		func(msg string) {
			_ = sse.SendEventMessage(msg)
		})

	_ = sse.SendEventMessage2(outFilename, "filename")

	var closeMsg string
	if err != nil {
		closeMsg = fmt.Sprintf("convert fail, err: %v", err)
	} else {
		closeMsg = fmt.Sprintf("convert success")
	}

	_ = sse.SendEventMessage2(closeMsg, "close")
}
